/** @file

Copyright (c) 2006-2023, Kunlun BIOS, Kunlun Technology (Beijing) Co., Ltd.. All
Rights Reserved.

You may not reproduce, distribute, publish, display, perform, modify, adapt,
transmit, broadcast, present, recite, release, license or otherwise exploit
any part of this publication in any form, by any means, without the prior
written permission of Kunlun Technology (Beijing) Co., Ltd..

Module Name:


Abstract:


Revision History:

**/


#include <Uefi.h>

#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/PcdLib.h>
#include <Protocol/LockBox.h>
#include <LockBoxLib.h>

/**
  Allocate memory below 4G memory address.

  This function allocates memory below 4G memory address.

  @param  MemoryType   Memory type of memory to allocate.
  @param  Size         Size of memory to allocate.

  @return Allocated address for output.

**/
STATIC
VOID *
AllocateMemoryBelow4G (
  IN EFI_MEMORY_TYPE    MemoryType,
  IN UINTN              Size
  )
{
  UINTN                 Pages;
  EFI_PHYSICAL_ADDRESS  Address;
  EFI_STATUS            Status;
  VOID*                 Buffer;
  UINTN                 AllocRemaining;
  LOCK_BOX_GLOBAL       *LockBoxGlobal;

  LockBoxGlobal = (LOCK_BOX_GLOBAL *)(UINTN) PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageBase);
  Pages = EFI_SIZE_TO_PAGES (Size);
  Address = 0xffffffff;

  //
  // Since we need to use gBS->AllocatePages to get a buffer below
  // 4GB, there is a good chance that space will be wasted for very
  // small allocation. We keep track of unused portions of the page
  // allocations, and use these to allocate memory for small buffers.
  //
  ASSERT (LockBoxGlobal->Signature == LOCK_BOX_GLOBAL_SIGNATURE);
  if ((UINTN) LockBoxGlobal->SubPageRemaining >= Size) {
    Buffer = (VOID*)(UINTN) LockBoxGlobal->SubPageBuffer;
    LockBoxGlobal->SubPageBuffer += (UINT32) Size;
    LockBoxGlobal->SubPageRemaining -= (UINT32) Size;
    return Buffer;
  }

  Status  = gBS->AllocatePages (
                   AllocateMaxAddress,
                   MemoryType,
                   Pages,
                   &Address
                   );
  if (EFI_ERROR (Status)) {
    return NULL;
  }

  Buffer = (VOID *) (UINTN) Address;
  ZeroMem (Buffer, EFI_PAGES_TO_SIZE (Pages));

  AllocRemaining = EFI_PAGES_TO_SIZE (Pages) - Size;
  if (AllocRemaining > (UINTN) LockBoxGlobal->SubPageRemaining) {
    LockBoxGlobal->SubPageBuffer = (UINT32) (Address + Size);
    LockBoxGlobal->SubPageRemaining = (UINT32) AllocRemaining;
  }

  return Buffer;
}


/**
  Allocates a buffer of type EfiACPIMemoryNVS.

  Allocates the number bytes specified by AllocationSize of type
  EfiACPIMemoryNVS and returns a pointer to the allocated buffer.
  If AllocationSize is 0, then a valid buffer of 0 size is
  returned.  If there is not enough memory remaining to satisfy
  the request, then NULL is returned.

  @param  AllocationSize        The number of bytes to allocate.

  @return A pointer to the allocated buffer or NULL if allocation fails.

**/
VOID *
EFIAPI
AllocateAcpiNvsPool (
  IN UINTN  AllocationSize
  )
{
  return AllocateMemoryBelow4G (EfiReservedMemoryType, AllocationSize);
}


/**
  The event callback of ready to boot.

  @param  Event        The event of  ready to boot.
  @param  Context      a pointer to The event context.

**/
VOID
EFIAPI
LockBoxReadyToBootEvent (
  EFI_EVENT                               Event,
  VOID                                    *Context
  )
{
  EFI_STATUS                      Status;
  LOCK_BOX_GLOBAL                 *LockBoxGlobal;

  LockBoxGlobal = (LOCK_BOX_GLOBAL *)(UINTN) PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageBase);
  //
  // Save runtime script table base into global Lock Box variable
  //
  Status = gRT->SetVariable (
                  LOCK_BOX_GLOBAL_VARIABLE,
                  &gEfiLockBoxGlobalGuid,
                  EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
                  sizeof(UINT64),
                  &LockBoxGlobal
                  );
  if (EFI_ERROR(Status)) {
    return;
  }

  gBS->CloseEvent (Event);
}

/**
  Main entry for this driver.

  @param ImageHandle     Image handle this driver.
  @param SystemTable     Pointer to SystemTable.

  @retval EFI_SUCESS     This function complete successfully.

**/
EFI_STATUS
EFIAPI
LockBoxDxeLibInitialize (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS                      Status;
  EFI_PHYSICAL_ADDRESS            Buffer;
  EFI_EVENT                       LockBoxEvent;
  VOID                            *Interface;
  LOCK_BOX_GLOBAL                 *LockBoxGlobal;

  if (PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageSize) < sizeof (LOCK_BOX_GLOBAL)) {
    return RETURN_UNSUPPORTED;
  }

  LockBoxGlobal = (LOCK_BOX_GLOBAL *)(UINTN) PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageBase);
  DEBUG ((DEBUG_INFO, "LockBoxGlobal  = %lx \n",LockBoxGlobal));
  if (LockBoxGlobal == 0) {
    //
    // The Lock Box Global data is not be initialized. create it
    //
    Buffer = SIZE_4GB - 1;
    Status = gBS->AllocatePages (
                    AllocateMaxAddress,
                    EfiReservedMemoryType,
                    EFI_SIZE_TO_PAGES(PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageSize) ),
                    &Buffer
                    );
    ASSERT_EFI_ERROR (Status);
    LockBoxGlobal = (VOID *) (UINTN) Buffer;
    ZeroMem(LockBoxGlobal, PcdGetEx64 (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageSize) );

    ASSERT (LockBoxGlobal);

    Status = PcdSetEx64S (&gKlModulePkgTokenSpaceGuid,PcdLockBoxStorageBase, (UINT64) (UINTN)LockBoxGlobal);
    ASSERT_EFI_ERROR (Status);

    DEBUG ((DEBUG_INFO, "LockBoxGlobal  = %lx \n",LockBoxGlobal));

    EfiCreateEventReadyToBootEx (
                           TPL_CALLBACK,
                           LockBoxReadyToBootEvent,
                           NULL,
                           &LockBoxEvent
                           );
    ASSERT_EFI_ERROR (Status);
  }

  Status = LockBoxLibInitialize ();
//[gliu-0049]add-begin
  //AllocateAcpiNvsPool(0x8);
  if (!EFI_ERROR (Status)) {
    if (PcdGetBool (PcdAcpiS3Enable)) {
      //
      // When S3 enabled, the first driver run with this library linked will
      // have this library constructor to install LockBox protocol on the
      // ImageHandle. As other drivers may have gEfiLockBoxProtocolGuid
      // dependency, the first driver should run before them.
      //
      Status = gBS->LocateProtocol (&gEfiLockBoxProtocolGuid, NULL, &Interface);
      if (EFI_ERROR (Status)) {
        Status = gBS->InstallProtocolInterface (
                        &ImageHandle,
                        &gEfiLockBoxProtocolGuid,
                        EFI_NATIVE_INTERFACE,
                        NULL
                        );
        DEBUG ((DEBUG_INFO, "Install LockBoxGlobal Protocol  = %r \n",Status));
        ASSERT_EFI_ERROR (Status);
      }
    }
  }
//[gliu-0049]add-end
  return Status;
}
